import router from './router'
import store from './store'
import { Message } from 'element-ui';
import ResponseUtil from '@/utils/response';
import BaseErrorCode from '@/constants/error-code';
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { isPathMatch } from '@/utils/validate'
import { isRelogin } from '@/utils/request'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/register']

const isWhiteList = (path) => {
  return whiteList.some(pattern => isPathMatch(pattern, path))
}

router.beforeEach(async(to, from, next) => {
  try {
    NProgress.start()
    if (getToken()) {
      to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
      /* has token*/
      if (to.path === '/login') {
        next({ path: '/' })
        NProgress.done()
      } else if (isWhiteList(to.path)) {
        next()
      } else {
        if (store.getters.roles.length === 0) {
          isRelogin.show = true
          // 判断当前用户是否已拉取完user_info信息
          store.dispatch('GetInfo').then(() => {
            isRelogin.show = false
            store.dispatch('GenerateRoutes').then(accessRoutes => {
              // 根据roles权限生成可访问的路由表
              router.addRoutes(accessRoutes) // 动态添加可访问路由表
              next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
            })
          }).catch(err => {
              store.dispatch('LogOut').then(() => {
                Message.error(err)
                next({ path: '/' })
              })
            })
        } else {
          // 添加token刷新逻辑
          if (store.getters.isTokenExpired) {
            store.dispatch('RefreshToken').catch(error => {
              Message.error('刷新token失败，请重新登录')
              store.dispatch('LogOut').then(() => {
                next({ path: '/' })
              })
            })
          }
          if (to.meta && to.meta.permissions) {
            const permissions = await getCurrentUserPermissions(); // 获取当前用户的所有权限
            const hasPermission = permissions.some(permission => {
              // 使用正则匹配检查权限
              return new RegExp(permission).test(to.path);
            });
            
            if (!hasPermission) {
              ResponseUtil.write(response, BaseErrorCode.FORBIDDEN); // 统一返回403状态码
              return false;
            } else {
              next()
            }
          } else {
            next()
          }
        }
      }
    } else {
      // 没有token
      if (isWhiteList(to.path)) {
        // 在免登录白名单，直接进入
        next()
      } else {
        next(`/login?redirect=${encodeURIComponent(to.fullPath)}`) // 否则全部重定向到登录页
        NProgress.done()
      }
    }
  } catch (error) {
    console.error('路由守卫发生错误:', error);
    Message.error('系统发生错误，请重新登录');
    store.dispatch('LogOut');
    next({ path: '/login' });
  }
})

router.afterEach(() => {
  NProgress.done()
})